const WebSocket = require('ws');

class Test4437FieldMapping {
    constructor() {
        this.ws = null;
        this.testResults = [];
    }

    async connect() {
        return new Promise((resolve, reject) => {
            this.ws = new WebSocket('ws://localhost:3000/user-service/websocket?t=test-token');

            this.ws.on('open', () => {
                console.log('✅ WebSocket连接成功');
                resolve();
            });

            this.ws.on('error', (error) => {
                console.error('❌ WebSocket连接失败:', error.message);
                reject(error);
            });

            this.ws.on('close', () => {
                console.log('🔌 WebSocket连接关闭');
            });
        });
    }

    async test4437FieldMapping() {
        console.log('\n🧪 测试4437指令字段映射...');

        // 测试用例1: 支援魏国100金币
        console.log('\n📝 测试用例1: 支援魏国100金币');
        const testCase1 = {
            c: 4437,
            d: { side: "1", type: "1", bet: 100 }
        };

        try {
            const result1 = await this.sendAndWait(testCase1);
            this.recordTest('4437-魏国金币', 'PASS', result1);
            console.log('✅ 测试用例1通过:', result1);
        } catch (error) {
            this.recordTest('4437-魏国金币', 'FAIL', null, error.message);
            console.log('❌ 测试用例1失败:', error.message);
        }

        // 测试用例2: 支援蜀国200银币
        console.log('\n📝 测试用例2: 支援蜀国200银币');
        const testCase2 = {
            c: 4437,
            d: { side: "2", type: "2", bet: 200 }
        };

        try {
            const result2 = await this.sendAndWait(testCase2);
            this.recordTest('4437-蜀国银币', 'PASS', result2);
            console.log('✅ 测试用例2通过:', result2);
        } catch (error) {
            this.recordTest('4437-蜀国银币', 'FAIL', null, error.message);
            console.log('❌ 测试用例2失败:', error.message);
        }

        // 测试用例3: 支援吴国150金币
        console.log('\n📝 测试用例3: 支援吴国150金币');
        const testCase3 = {
            c: 4437,
            d: { side: "3", type: "1", bet: 150 }
        };

        try {
            const result3 = await this.sendAndWait(testCase3);
            this.recordTest('4437-吴国金币', 'PASS', result3);
            console.log('✅ 测试用例3通过:', result3);
        } catch (error) {
            this.recordTest('4437-吴国金币', 'FAIL', null, error.message);
            console.log('❌ 测试用例3失败:', error.message);
        }

        // 测试用例4: 缺少必需字段
        console.log('\n📝 测试用例4: 缺少必需字段');
        const testCase4 = {
            c: 4437,
            d: { side: "1", type: "1" } // 缺少bet字段
        };

        try {
            const result4 = await this.sendAndWait(testCase4);
            this.recordTest('4437-缺少字段', 'PASS', result4);
            console.log('✅ 测试用例4通过:', result4);
        } catch (error) {
            this.recordTest('4437-缺少字段', 'FAIL', null, error.message);
            console.log('❌ 测试用例4失败:', error.message);
        }
    }

    sendAndWait(data) {
        return new Promise((resolve, reject) => {
            const timeout = setTimeout(() => {
                reject(new Error('请求超时'));
            }, 5000);

            this.ws.once('message', (message) => {
                clearTimeout(timeout);
                try {
                    const response = JSON.parse(message.toString());
                    resolve(response);
                } catch (error) {
                    reject(new Error('响应解析失败: ' + error.message));
                }
            });

            this.ws.send(JSON.stringify(data));
        });
    }

    recordTest(testName, status, result, error = null) {
        this.testResults.push({
            testName,
            status,
            result,
            error,
            timestamp: new Date().toISOString()
        });
    }

    printTestSummary() {
        console.log('\n📊 测试结果汇总:');
        console.log('='.repeat(50));

        const total = this.testResults.length;
        const passed = this.testResults.filter(r => r.status === 'PASS').length;
        const failed = this.testResults.filter(r => r.status === 'FAIL').length;

        console.log(`总测试数: ${total}`);
        console.log(`通过: ${passed} ✅`);
        console.log(`失败: ${failed} ❌`);
        console.log(`成功率: ${((passed / total) * 100).toFixed(1)}%`);

        console.log('\n详细结果:');
        this.testResults.forEach((result, index) => {
            const statusIcon = result.status === 'PASS' ? '✅' : '❌';
            console.log(`${index + 1}. ${statusIcon} ${result.testName}: ${result.status}`);
            if (result.error) {
                console.log(`   错误: ${result.error}`);
            }
            if (result.result) {
                console.log(`   响应: ${JSON.stringify(result.result, null, 2)}`);
            }
        });
    }

    async run() {
        try {
            await this.connect();
            await this.test4437FieldMapping();
            this.printTestSummary();
        } catch (error) {
            console.error('测试运行失败:', error.message);
        } finally {
            if (this.ws) {
                this.ws.close();
            }
        }
    }
}

// 运行测试
if (require.main === module) {
    const tester = new Test4437FieldMapping();
    tester.run().catch(console.error);
}

module.exports = Test4437FieldMapping; 